<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:change:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:change:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:change:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:change:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="changeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="sn" />
      <el-table-column label="换货时间" align="center" prop="changeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.changeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="服务专员名称" align="center" prop="staffName" />
      <el-table-column label="换货金额" align="center" prop="changeAmount" />
      <el-table-column label="登记人" align="center" prop="handledBy" />
      <el-table-column label="审核人" align="center" prop="auditPersonName" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.auditPersonName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusTagType(scope.row.status)"
            effect="dark">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:change:edit']"
            v-if="scope.row.status !== 2"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:change:remove']"
            v-if="scope.row.status !== 2"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['system:change:edit']"
            v-if="scope.row.status === 0"
          >提交</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:change:audit']"
            v-if="scope.row.status === 1"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改换货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="sn">
          <el-input
            v-model="form.sn"
            placeholder="请输入编号"
            :disabled="form.isAdd"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择部门名称"
            clearable
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库名称"
            clearable
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="换货金额" prop="changeAmount">
          <el-input v-model="form.changeAmount" placeholder="请输入换货金额" />
        </el-form-item>

        <el-form-item label="经手人">
          <el-cascader
            v-model="form.handledById"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择经手人"
            @change="handleCreatorChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="换货说明" prop="changeDesc">
          <el-input v-model="form.changeDesc" placeholder="请输入换货说明" />
        </el-form-item>
        <el-form-item label="换货时间" prop="changeTime">
          <el-date-picker clearable
                          v-model="form.changeTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择换货时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
<!--      <el-button-->
<!--        size="mini"-->
<!--        type="text"-->
<!--        icon="el-icon-goods"-->
<!--        @click="handleViewProducts(scope.row)"-->
<!--        v-hasPermi="['system:change:query']"-->
<!--      >商品明细</el-button>-->

      <!-- 添加商品明细弹窗 -->
      <el-dialog
        title="换货商品明细"
        :visible.sync="productDialog.visible"
        width="90%"
        append-to-body>
        <el-table
          :data="productDialog.products"
          border
          style="width: 100%"
          height="500">
          <el-table-column prop="stockSn" label="入库单号" width="180" align="center"></el-table-column>
          <el-table-column prop="productSn" label="商品编号" width="120" align="center"></el-table-column>
          <el-table-column prop="productName" label="商品名称" width="150" align="center"></el-table-column>
          <el-table-column prop="specification" label="规格型号" width="120" align="center"></el-table-column>
          <el-table-column prop="unit" label="单位" width="80" align="center"></el-table-column>
          <el-table-column prop="costPrice" label="单价" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.costPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量" width="100" align="center"></el-table-column>
          <el-table-column prop="amount" label="金额" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteProduct(scope.row.id)"
                v-hasPermi="['system:change:edit']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="openAddProductDialog">添加商品</el-button>
          <el-button @click="productDialog.visible = false">关闭</el-button>
        </div>
      </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      title="换货单审核"
      :visible.sync="auditDialog.visible"
      width="500px"
      append-to-body>
      <el-form ref="auditForm" :model="auditDialog.form" :rules="auditDialog.rules" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditDialog.form.status">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="拒绝原因"
          prop="rejectReason"
          v-if="auditDialog.form.status === 3">
          <el-input
            v-model="auditDialog.form.rejectReason"
            type="textarea"
            placeholder="请输入拒绝原因"
            :rows="3"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {
  listChange,
  getChange,
  delChange,
  addChange,
  updateChange,
  delChangeProduct,
  addChangeProduct, getChangeProducts
} from "@/api/system/change";
import { listDept } from "@/api/erpsystem/dept";
import { listWarehouse } from "@/api/system/warehouse";
import {
  getCompiler,
} from "@/api/procurementmanagement/plan";


export default {
  name: "Change",
  data() {
    return {
      productDialog: {
        visible: false,
        products: [],
        currentChangeId: null
      },
      auditDialog: {
        visible: false,
        form: {
          id: null,
          status: 2, // 2通过 3拒绝
          rejectReason: null,
          auditPersonId: null,
          auditPersonName: null
        },
        rules: {
          status: [
            { required: true, message: '请选择审核结果', trigger: 'change' }
          ],
          rejectReason: [
            { required: true, message: '拒绝原因不能为空', trigger: 'blur' },
            { min: 5, max: 200, message: '长度在5到200个字符', trigger: 'blur' }
          ]
        }
      },
      //制表人
      personList:[],
      // 遮罩层
      loading: true,
      // 部门选项
      deptOptions: [],
      // 仓库选项
      warehouseOptions: [],
      //用户选项
      userOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 换货单表格数据
      changeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        orderSn: null,
        staffId: null,
        staffName: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        changeAmount: null,
        handledById: null,
        handledBy: null,
        changeDesc: null,
        changeTime: null,
        status: null,
        rejectReason: null,
        submitTime: null,
        auditTime: null,
        auditPersonId: null,
        auditPersonName: null
      },
      //审核对话框
      auditOpen: false,
      auditForm: {
        id: null,
        status: 2,
        rejectReason: null,
        auditPersonId: null,
        auditPersonName: null
      },
      auditRules: {
        status: [{ required: true, message: "请选择审核结果", trigger: "change" }],
        rejectReason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" },
          { min: 2, max: 200, message: "长度在 2 到 200 个字符", trigger: "blur" }
        ]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.initData().catch(error => {
      console.error("初始化失败:", error);
    });
  },
  methods: {
    // 查看商品明细
    handleViewProducts(row) {
      this.productDialog.currentChangeId = row.id;
      this.loadProducts(row.id);
      this.productDialog.visible = true;
    },

    // 加载商品数据
    loadProducts(changeId) {
      getChangeProducts(changeId).then(response => {
        this.productDialog.products = response.data || response.rows || [];
      });
    },

    // 删除商品
    handleDeleteProduct(productId) {
      this.$modal.confirm('确认删除该商品？').then(() => {
        delChangeProduct([productId]).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.loadProducts(this.productDialog.currentChangeId);
        });
      }).catch(() => {});
    },

    // 打开添加商品对话框
    openAddProductDialog() {
      // 这里可以添加选择商品的逻辑
      this.$prompt('请输入商品编号', '添加商品', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        const newProduct = {
          changeId: this.productDialog.currentChangeId,
          productSn: value,
          productName: '新商品', // 实际应从接口获取
          specification: '',
          unit: '个',
          num: 1,
          costPrice: 0,
          amount: 0,
          type: 1
        };
        addChangeProduct(newProduct).then(() => {
          this.$modal.msgSuccess("添加成功");
          this.loadProducts(this.productDialog.currentChangeId);
        });
      }).catch(() => {});
    },
    async initData() {
      try {
        await this.getCompiler();
        await this.getList();
        await this.getDeptOptions();
        await this.getWarehouseOptions();
      } catch (error) {
        console.error("初始化错误:", error);
      }
    },

    getCompiler() {
      return new Promise((resolve, reject) => {
        getCompiler().then(response => {
          this.personList = response.data || response.rows || [];
          resolve(this.personList);
        }).catch(error => {
          console.error("获取编制人失败:", error);
          reject(error);
        });
      });
    },

    // 状态文本显示
    getStatusText(status) {
      const statusMap = {
        0: '未提交',
        1: '待审核',
        2: '已通过',
        3: '已拒绝'
      }
      return statusMap[status] || '未知状态'
    },

    // 状态标签颜色
    getStatusTagType(status) {
      const colorMap = {
        0: 'info',    // 灰色
        1: 'warning', // 黄色
        2: 'success', // 绿色
        3: 'danger'   // 红色
      }
      return colorMap[status] || ''
    },

    // 提交审核
    handleSubmit(row) {
      this.$modal.confirm('确认提交换货单编号为"' + row.sn + '"的数据项？').then(() => {
        const form = {
          id: row.id,
          status: 1,
          submitTime: new Date()
        };
        updateChange(form).then(response => {
          this.$modal.msgSuccess("提交成功");
          this.getList();
        });
      }).catch(() => {});
    },

    // 打开审核对话框
    async handleAudit(row) {
      try {
        await this.getCompiler();

        // 从store获取当前用户信息
        const user = this.$store.state.user || this.$store.getters.user;

        // 设置审核表单初始值
        this.auditDialog.form = {
          id: row.id,
          status: 2, // 默认通过
          rejectReason: null,
          auditPersonId: user?.userId || user?.id,
          auditPersonName: user?.nickName || user?.name || user?.realName
        };
        this.auditDialog.visible = true;
      } catch (error) {
        console.error("审核错误:", error);
        this.$modal.msgError("获取用户信息失败，请检查登录状态");
      }
    },

// 提交审核
    handleAuditSubmit() {
      this.$refs.auditForm.validate(valid => {
        if (!valid) return;

        const params = {
          id: this.auditDialog.form.id,
          status: this.auditDialog.form.status,
          rejectReason: this.auditDialog.form.status === 3 ? this.auditDialog.form.rejectReason : null,
          auditPersonId: this.auditDialog.form.auditPersonId,
          auditPersonName: this.auditDialog.form.auditPersonName,
          auditTime: new Date()
        };

        updateChange(params).then(response => {
          this.$modal.msgSuccess("审核成功");
          this.auditDialog.visible = false;
          this.getList();
        }).catch(error => {
          this.$modal.msgError(error.message || "审核失败");
        });
      });
    },

    // 取消审核
    cancelAudit() {
      this.auditOpen = false;
      this.resetAuditForm();
    },

    // 重置审核表单
    resetAuditForm() {
      this.auditForm = {
        id: null,
        status: 2,
        rejectReason: null,
        auditPersonId: null,
        auditPersonName: null
      };
    },
    /** 获取部门列表 */
    getDeptOptions() {
      listDept().then(response => {
        response.data.forEach(dept => {
          dept.deptName = dept.name;
        });
        this.deptOptions = response.data;
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    /** 获取用户列表 */
    getUserOptions() {
      // 修改为更健壮的实现
      if (!this.$store.getters.user) {
        console.warn('用户信息未获取到');
        return;
      }

      // 使用正确的API方法名（根据实际API调整）
      getCompiler().then(response => {
        this.userOptions = response.rows;
      }).catch(error => {
        console.error('获取用户列表失败:', error);
      });
    },
    /** 查询换货单列表 */
    getList() {
      this.loading = true;
      listChange(this.queryParams).then(response => {
        this.changeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        orderSn: null,
        staffId: null,
        staffName: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        changeAmount: null,
        handledById: null,
        handledBy: null,
        changeDesc: null,
        changeTime: null,
        createTime: null,
        status: null,
        rejectReason: null,
        submitTime: null,
        auditTime: null,
        auditPersonId: null,
        auditPersonName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isAdd = true; // 设置新增标识
      this.form.sn = this.generateRandomSn(); // 生成随机编号（包含前缀）
      this.getCompiler(); // 获取编制人
      this.open = true;
      this.title = "添加库存盘点单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getChange(id).then(response => {
        this.form = response.data;
        this.getCompiler(); // 获取编制人
        this.form.isAdd = false; // 设置为修改操作
        this.open = true;
        this.title = "修改换货单";
      });
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.handledById = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.handledBy = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.handledById = null;
        this.form.handledBy = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.planList = this.planList;
          if (this.form.id != null) {
            updateChange(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChange(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除换货单编号为"' + ids + '"的数据项？').then(function() {
        return delChange(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/change/export', {
        ...this.queryParams
      }, `change_${new Date().getTime()}.xlsx`)
    },
    generateRandomSn() {
      const prefix = "HH"; // 随机编号前缀
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${prefix}${year}${month}${day}${randomNum}`; // 拼接前缀和随机编号
    },
  }
};
</script>

